package com.truongnha.clienttn.presentation.temp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.truongnha.clienttn.data.servicehelper.utils;

//import SessionManager.CookieManager;
import android.content.Context;
import android.os.StrictMode;
import android.util.Log;

public class JSONParser {
	// static DefaultHttpClient httpClientStatic = new DefaultHttpClient();
	private static DefaultHttpClient client;
	static DefaultHttpClient httpClientStatic = JSONParser
			.getThreadSafeClient();
	static InputStream is = null;
	static JSONObject jObj = null;
	static JSONArray jArr = null;
	static String json = "";

	// constructor
	public JSONParser() {
		Log.d("parser constructer ", "construnctor");
		// This snipset allow stricmode in android network. It should be allow
		// from android 3.0 and later
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
	}

	// Test parsing without parameters:
	public static JSONObject getJSONFromUrl(String url) {
		Log.e("JSON", "01 ");
		// Making HTTP request
		InputStream is = null;
		try {
			Log.e("JSON", "02 ");

			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			Log.e("JSON", "03 ");
			HttpResponse httpResponse = httpClient.execute(httpPost);
			Log.e("JSON", httpResponse.getStatusLine().toString());
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
			Log.e("JSON", "04 ");

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		Log.e("JSON", "05 ");

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			Log.e("JSON", "06 ");

			StringBuilder sb = new StringBuilder();
			String line = null;
			Log.e("JSON", "07 ");

			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}
		Log.e("JSON", "08 ");

		// try parse the string to a JSON object
		try {
			Log.e("JSON", "09 ");

			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}
		Log.e("JSON", "10 ");

		// return JSON String
		Log.d("JSON Parser result: ", "done" + json);
		return jObj;
	}// End test parsing JSON.

	/*
	 * 1. HttpGet: return 200 Ok + csrftoken + cookies 2. HttpPost: params:
	 * middlewarecsrftoken: -------------------- cookies: --------------
	 * username: --------- pass: -------- 3. Done
	 */

	public String getCsrfFromUrl(String url) {
		try {
			jObj = utils.getJSONObjectByHttpGet(url);
			Log.d("JSON csrfmiddlewaretoken",
					jObj.getString("csrfmiddlewaretoken"));
			return jObj.getString("csrfmiddlewaretoken");
		} catch (Exception e) {
			Log.e("LOG error", e.toString());
			return null;
		}
	}

	// Return jsonObject
	public static JSONObject getStudentList(String url) {
		// Making HTTP GET request to get studentList:
		Log.e("URL", url);
		InputStream is = null;
		try {
			HttpGet httpGet = new HttpGet(url);
			// HttpResponse httpResponse = httpClientStatic.execute(httpGet);
			HttpResponse httpResponse = JSONParser.getThreadSafeClient()
					.execute(httpGet);
			Log.e("JSON GET", httpResponse.getStatusLine().toString() + "-");
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		// Read httpResponse to String
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			Log.e("JSON", "In getStudentList ");
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
			Log.e("JSON", json);
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
			return null;
		}

		// Try parse the string to a JSON object
		if (!json.equals("")) {
			try {
				jObj = new JSONObject(json);
			} catch (JSONException e) {
				Log.e("JSON Parser", "Error parsing data " + e.toString());
			}
		}
		return jObj;
	}

	// Return json array
	public JSONArray getStudentArray(String url) {
		// Making HTTP GET request to get studentList:
		Log.e("URL", url);
		InputStream is = null;
		try {
			HttpGet httpGet = new HttpGet(url);
			HttpResponse httpResponse = JSONParser.getThreadSafeClient()
					.execute(httpGet);
			Log.e("JSON GET", httpResponse.getStatusLine().toString() + "-");
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		// Read httpResponse to String
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			Log.e("JSON", "In getStudentList ");
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
			Log.e("JSON", json);
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
			return null;
		}

		JSONArray jArray = null;
		// Try parse the string to a JSON object
		if (!json.equals("")) {
			try {
				jArray = new JSONArray(json);
			} catch (JSONException e) {
				Log.e("JSON Parser", "Error parsing data " + e.toString());
			}
		}
		return jArray;
	}

	/*
	 * Get json object from url
	 */
	/* Post attendance result to server: */
	// This function is replaced by post submit. remove later.

	public int postStudentList(String postStudentListURL,
			List<NameValuePair> params) {
		int statusCode = 0;
		Log.e("JSON POst Student list", "01");
		try {
			Log.e("JSON POst Student list", "02");
			// defaultHttpClient
			// DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(postStudentListURL);
			Log.e("JSON POst Student list", "03");

			httpPost.setEntity(new UrlEncodedFormEntity(params));
			Log.e("JSON POst Student list", "035");
			HttpResponse httpResponse = JSONParser.getThreadSafeClient()
					.execute(httpPost);
			Log.e("JSON POst Student list", "04");

			statusCode = httpResponse.getStatusLine().getStatusCode();
			Log.e("JSON POst Student list", statusCode + "-");

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.e("JSON POst Student list", "05");
		return statusCode;
	}// end function

	/*
	 * function: postSubmit(URL, params) To post any params you want to URL:
	 * student attendenca list or student mark. The params include csrfToken,
	 * too.
	 */
	public int postSubmit(String URL, List<NameValuePair> params) {
		int statusCode = 0;
		Log.e("JSON submit", "01");
		try {
			Log.e("JSON submit", "02");
			// defaultHttpClient
			// DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(URL);
			Log.e("JSON submit", "03");

			httpPost.setEntity(new UrlEncodedFormEntity(params));
			Log.e("JSON submit", "035");
			HttpResponse httpResponse = JSONParser.getThreadSafeClient()
					.execute(httpPost);
			Log.e("JSON submit", "04");

			statusCode = httpResponse.getStatusLine().getStatusCode();
			Log.e("JSON submit", statusCode + "-");

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.e("in JSONParser URL", URL);
		return statusCode;
	}// end function

	public static DefaultHttpClient getThreadSafeClient() {
		if (client != null) {
			return client;
		}
		client = new DefaultHttpClient();
		ClientConnectionManager mgr = client.getConnectionManager();
		HttpParams params = client.getParams();
		client = new DefaultHttpClient(new ThreadSafeClientConnManager(params,
				mgr.getSchemeRegistry()), params);
		return client;
	}

	public boolean isSavedSession(Context context) {
		if (CookieManager.isSaved(context)) {
			List<Cookie> cookies = CookieManager.getCookies(context);
			for (Cookie cookie : cookies) {
				client.getCookieStore().addCookie(cookie);
			}
			return true;
		}
		return false;
	}

	public void clearSession(Context context) {
		CookieManager.clear(context);
	}

	public boolean logout(String url) {
		try {
			JSONObject result = utils.getJSONObjectByHttpGet(url);
		} catch (Exception e) {
			Log.e("LOG error", "error in logout" + e.toString());
			return false;
		}
		return true;

	}
}// end class